package com.chen10.gobang.common.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
@RequiredArgsConstructor
public class RedisUtil {

    private final RedisTemplate<String, Object> redisTemplate;

    public void setex(String key, Object value, Integer timeout, TimeUnit timeUnit) {
        redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
    }

    public void set(String key, Object value) {
        redisTemplate.opsForValue().set(key,value);
    }
    public Object get(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    public Boolean delete(String key) {
        return redisTemplate.delete(key);
    }


    //hash操作
    /**
     * 向哈希表中添加或更新字段
     */
    public void hset(String hashKey, String field, Object value){
        redisTemplate.opsForHash().put(hashKey, field, value);
    }

    /**
     * 向哈希表中添加或更新字段，设置过期时间
     */
    public void hsetex(String hashKey, String field, Object value, Integer timeout, TimeUnit timeUnit){
        redisTemplate.opsForHash().put(hashKey, field, value);
        redisTemplate.expire(hashKey, timeout, timeUnit);
    }
    /**
     * 从哈希表中获取指定字段的值
     */
    public Object hget(String hashKey, String field) {
        return redisTemplate.opsForHash().get(hashKey, field);
    }

    /**
     * 从哈希表中删除指定字段
     */
    public Long deleteFromHash(String hashKey, String field) {
        return redisTemplate.opsForHash().delete(hashKey, field);
    }

    /**
     * 检查哈希表中是否存在指定字段
     */
    public Boolean hasKeyInHash(String hashKey, String field) {
        return redisTemplate.opsForHash().hasKey(hashKey, field);
    }

    /**
     * 向哈希表中批量添加或更新字段
     */
    public void putAllInHash(String hashKey, Map<String, Object> values) {
        redisTemplate.opsForHash().putAll(hashKey, values);
    }
}
